import { ProForm, ProFormText, ProFormSelect, ProFormDatePicker, ProFormMoney, ProFormDigit, ProFormDependency } from '@ant-design/pro-components';
import { Col, Row, Space, message, Form, Button } from 'antd';
import { addMedicine, medicineIn, medicineRestExport } from '@/services/medicine'
import MedicineSearch from '@/components/MedicineSearch';
import { useState } from 'react'
import type { PatientsItem } from '@/interfaces/patients'
import { downloadFileWithToken } from '@/utils/download'

const AddForm = ({ onFinish, readonly, name = '' }) => {
    return (
        <ProForm< Partial<PatientsItem>>
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 14 }}
            layout='horizontal'
            grid
            submitter={{
                render: (props, doms) => {
                    return <Row>
                        <Col span={4} offset={20} >
                            <Space>{doms}</Space>
                        </Col>
                    </Row>
                },
            }}
            onFinish={async (values) => {
                let result;
                if (readonly) {
                    result = await medicineIn(values)
                } else {
                    result = await addMedicine(values)
                }
                if (result.code === 200) {
                    onFinish()
                    message.success('提交成功');
                } else {
                    message.error(result.message);
                }
            }}
            initialValues={{
                name: name
            }}
        >
            <ProFormText
                width="md"
                name="name"
                label="药品名称"
                readonly={readonly}
                placeholder="请输入药品名称"
                colProps={{ span: 12 }}
                rules={[{ required: true }]}
            />
            <ProFormText
                width="md"
                name="factory"
                label="生产厂家"
                placeholder="请输入生产厂家"
                colProps={{ span: 12 }}
                rules={[{ required: true }]}
            />
            <ProFormText
                width="md"
                name="specs"
                label="产品规格"
                placeholder="请输入产品规格"
                colProps={{ span: 12 }}
                rules={[{ required: true }]}
            />
            <ProFormSelect
                colProps={{ span: 12 }}
                label="剂型"
                name="type"
                valueEnum={{
                    '片剂': '片剂',
                    '酊剂': '酊剂',
                    '液体': '液体',
                    '针剂': '针剂',
                }}
                rules={[{ required: true }]}
            />
            <ProFormSelect
                colProps={{ span: 12 }}
                label="包装"
                name="pack"
                valueEnum={{
                    '盒': '盒',
                    '箱': '箱',
                    '瓶': '瓶',
                    '袋': '袋',
                }}
                rules={[{ required: true }]}
            />
            <ProFormMoney colProps={{ span: 12 }}
                label="单价"
                name="price"
                rules={[{ required: true }]}
            />
            <ProFormDigit colProps={{ span: 12 }}
                label="入库数量"
                name="entercount"
                rules={[{ required: true }]}
            />

            <ProFormDependency name={['price', 'entercount']}>
                {({ price, entercount }) => {
                    return (
                        <ProFormMoney
                            colProps={{ span: 12 }}
                            width="md"
                            name="totalprice"
                            label='总计金额'
                            disabled
                            convertValue={() => {
                                return `${(price || 0) * (entercount || 0)}`
                            }}
                        />
                    );
                }}
            </ProFormDependency>

            <ProFormText
                width="md"
                name="batchnumber"
                label="生产批号"
                colProps={{ span: 12 }}
                rules={[{ required: true }]}
            />
            <ProFormDatePicker
                width="md"
                name="productdate"
                label="生产日期"
                rules={[{ required: true }]}
                placeholder="请选择生产日期"
                colProps={{ span: 12 }}
            />
            <ProFormDependency name={['productdate']}>
                {({ productdate }) => {
                    return (<ProFormDatePicker
                        width="md"
                        name="deaddate"
                        label="截止有效期"
                        rules={[{
                            required: true, validator: (_, value) => {
                                if (value && productdate && new Date(value).getTime() < new Date(productdate).getTime()) {
                                    return Promise.reject(new Error('截止有效期不能小于生产日期'));
                                }
                                return Promise.resolve();
                            }
                        }]}
                        placeholder="请选择截止日期"
                        colProps={{ span: 12 }}
                    />)
                }}
            </ProFormDependency>

        </ProForm>
    )
}

const ExportRest = ({ onExportFinish }) => {
    const [loading, setLoading] = useState(false);
    const handleFinish = async (values) => {
        try {
            const blob = await medicineRestExport(values)
            // 获取当前日期
            const date = new Date().toLocaleDateString().replace(/\//g, '-')
            downloadFileWithToken(blob, '结存导出结果' + date + '.xlsx')
            message.success('导出成功')
        } catch (error) {
            message.error('导出失败，请刷新后尝试')
        } finally {
            setLoading(false)
            onExportFinish()
        }
    }
    return <Form
        name="basic"
        labelCol={{ span: 8 }}
        style={{ maxWidth: 600 }}
        onFinish={handleFinish}
        autoComplete="off"
    >
        <Form.Item
            label="药品名称"
            name="name"
        >
            <MedicineSearch />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit" onClick={() => setLoading(true)} loading={loading}>
                提交
            </Button>
        </Form.Item>
    </Form >
}

export {
    AddForm,
    ExportRest
} 